<!-- components/template-designer/renderers/LayoutTableRenderer.vue -->
<template>
  <div class="layout-table-renderer" :style="containerStyle">
    <!-- 设计模式 -->
    <div v-if="mode === 'design'" class="table-design-mode">
      <!-- 可编辑表格 -->
      <div class="editable-table-container" ref="tableContainer">
        <table class="layout-table" :style="tableStyle" ref="tableElement">
          <tbody>
            <tr
              v-for="(row, rowIndex) in tableData.rows"
              :key="rowIndex"
              :style="getRowStyle(rowIndex)"
            >
              <td
                v-for="(cell, colIndex) in row.cells"
                :key="colIndex"
                :style="getCellStyle(rowIndex, colIndex)"
                :class="[
                  'layout-cell',
                  {
                    'selected': isCellSelected(rowIndex, colIndex),
                    'merged': isCellMerged(rowIndex, colIndex),
                    'drop-target': isDropTarget(rowIndex, colIndex)
                  }
                ]"
                @click="selectCell(rowIndex, colIndex, $event)"
                @contextmenu="showContextMenu(rowIndex, colIndex, $event)"
                @drop="handleDrop(rowIndex, colIndex, $event)"
                @dragover="handleDragOver(rowIndex, colIndex, $event)"
                @dragenter="handleDragEnter(rowIndex, colIndex, $event)"
                @dragleave="handleDragLeave(rowIndex, colIndex, $event)"
              >
                <!-- 合并单元格显示 -->
                <div
                  v-if="isMergeStartCell(rowIndex, colIndex)"
                  class="merged-cell-content"
                  :rowspan="getMergeRowSpan(rowIndex, colIndex)"
                  :colspan="getMergeColSpan(rowIndex, colIndex)"
                >
                  <!-- 合并单元格中的组件 -->
                  <template-renderer
                    :components="getCellComponents(rowIndex, colIndex)"
                    :config="config"
                    :mode="mode"
                    :test-data="testData"
                    @select-component="handleComponentSelect"
                    @update-component="handleComponentUpdate"
                    @component-remove="handleComponentRemove"
                  />
                </div>
                
                <!-- 普通单元格内容 -->
                <div
                  v-else-if="!isCellMerged(rowIndex, colIndex)"
                  class="cell-content"
                >
                  <!-- 单元格中的组件 -->
                  <template-renderer
                    :components="cell.components || []"
                    :config="config"
                    :mode="mode"
                    :test-data="testData"
                    @select-component="handleComponentSelect"
                    @update-component="handleComponentUpdate"
                    @component-remove="handleComponentRemove"
                  />
                  
                  <!-- 空单元格提示 -->
                  <div
                    v-if="!cell.components || cell.components.length === 0"
                    class="empty-cell-hint"
                  >
                    <i class="el-icon-upload"></i>
                    <span>拖拽组件到此处</span>
                  </div>
                </div>

                <!-- 单元格尺寸显示 -->
                <div v-if="isCellSelected(rowIndex, colIndex)" class="cell-size-info">
                  {{ cell.width }}×{{ cell.height }}
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 右键菜单 -->
      <div
        v-if="contextMenu.visible"
        class="context-menu"
        :style="contextMenu.style"
        @mouseleave="hideContextMenu"
      >
        <div class="menu-section">
          <div class="menu-title">行操作</div>
          <div class="menu-item" @click="insertRow('above')">
            <i class="el-icon-top"></i>上方插入行
          </div>
          <div class="menu-item" @click="insertRow('below')">
            <i class="el-icon-bottom"></i>下方插入行
          </div>
          <div class="menu-item" @click="deleteRow()">
            <i class="el-icon-remove"></i>删除行
          </div>
        </div>

        <div class="menu-section">
          <div class="menu-title">列操作</div>
          <div class="menu-item" @click="insertColumn('left')">
            <i class="el-icon-back"></i>左侧插入列
          </div>
          <div class="menu-item" @click="insertColumn('right')">
            <i class="el-icon-right"></i>右侧插入列
          </div>
          <div class="menu-item" @click="deleteColumn()">
            <i class="el-icon-remove"></i>删除列
          </div>
        </div>

        <div class="menu-section">
          <div class="menu-title">合并操作</div>
          <div class="menu-item" @click="mergeCells('right')" :class="{ 'disabled': !canMergeRight }">
            <i class="el-icon-d-arrow-right"></i>合并右侧单元格
          </div>
          <div class="menu-item" @click="mergeCells('below')" :class="{ 'disabled': !canMergeBelow }">
            <i class="el-icon-d-arrow-down"></i>合并下方单元格
          </div>
          <div class="menu-item" @click="mergeCells('row')" :class="{ 'disabled': !canMergeRow }">
            <i class="el-icon-sort"></i>合并整行
          </div>
          <div class="menu-item" @click="mergeCells('column')" :class="{ 'disabled': !canMergeColumn }">
            <i class="el-icon-sort"></i>合并整列
          </div>
          <div class="menu-item" @click="splitCell()" :class="{ 'disabled': !canSplit }">
            <i class="el-icon-rank"></i>拆分单元格
          </div>
        </div>

        <div class="menu-section">
          <div class="menu-title">单元格属性</div>
          <div class="menu-item" @click="showCellProperties()">
            <i class="el-icon-setting"></i>设置宽度高度
          </div>
        </div>
      </div>

      <!-- 单元格属性对话框 -->
      <el-dialog
        title="单元格属性"
        :visible.sync="cellPropertiesDialog.visible"
        width="400px"
        :close-on-click-modal="false"
      >
        <el-form :model="cellPropertiesDialog.data" label-width="80px" size="mini">
          <el-form-item label="宽度">
            <el-input-number
              v-model="cellPropertiesDialog.data.width"
              :min="30"
              :max="500"
              controls-position="right"
            />
          </el-form-item>
          <el-form-item label="高度">
            <el-input-number
              v-model="cellPropertiesDialog.data.height"
              :min="20"
              :max="500"
              controls-position="right"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cellPropertiesDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="updateCellProperties">确定</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 预览和生成模式 -->
    <div v-else class="table-preview-mode">
      <table class="preview-layout-table" :style="tableStyle">
        <tbody>
          <tr v-for="(row, rowIndex) in tableData.rows" :key="rowIndex">
            <td
              v-for="(cell, colIndex) in row.cells"
              :key="colIndex"
              :style="getCellStyle(rowIndex, colIndex)"
              :rowspan="getMergeRowSpan(rowIndex, colIndex)"
              :colspan="getMergeColSpan(rowIndex, colIndex)"
            >
              <template-renderer
                v-if="isMergeStartCell(rowIndex, colIndex) || !isCellMerged(rowIndex, colIndex)"
                :components="getCellComponents(rowIndex, colIndex)"
                :config="config"
                :mode="mode"
                :test-data="testData"
              />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import { deepClone, generateId } from '@/utils/tools'
import TemplateRenderer from '../TemplateRenderer.vue'

export default {
  name: 'LayoutTableRenderer',
  components: {
    TemplateRenderer
  },
  props: {
    component: {
      type: Object,
      required: true
    },
    config: {
      type: Object,
      default: () => ({})
    },
    mode: {
      type: String,
      default: 'design'
    },
    testData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // 表格数据 - 直接管理，确保响应式
      tableData: {
        rows: [],
        merges: []
      },
      
      // 选中状态
      selectedCell: null,
      selectedRow: null,
      selectedCol: null,
      
      // 右键菜单
      contextMenu: {
        visible: false,
        row: null,
        col: null,
        style: {}
      },
      
      // 拖拽状态
      dropTargetCell: null,
      
      // 单元格属性对话框
      cellPropertiesDialog: {
        visible: false,
        data: {
          width: 150,
          height: 100
        }
      },
      
      // 默认配置
      defaultConfig: {
        rows: [
          {
            height: 100,
            cells: [
              { width: 150, height: 100, components: [] },
              { width: 150, height: 100, components: [] },
              { width: 150, height: 100, components: [] }
            ]
          },
          {
            height: 100,
            cells: [
              { width: 150, height: 100, components: [] },
              { width: 150, height: 100, components: [] },
              { width: 150, height: 100, components: [] }
            ]
          }
        ],
        merges: []
      }
    }
  },
  computed: {
    // 容器样式
    containerStyle() {
      return {
        width: '100%',
        height: '100%',
        padding: '8px',
        boxSizing: 'border-box',
        overflow: 'auto'
      }
    },
    
    // 表格样式
    tableStyle() {
      return {
        borderCollapse: 'collapse',
        width: '100%',
        minWidth: `${this.getTotalTableWidth()}px`
      }
    },
    
    // 合并操作可用性
    canMergeRight() {
      if (this.selectedCol === null) return false
      return this.selectedCol < this.tableData.rows[0].cells.length - 1 &&
             !this.isCellMerged(this.selectedRow, this.selectedCol + 1)
    },
    
    canMergeBelow() {
      if (this.selectedRow === null) return false
      return this.selectedRow < this.tableData.rows.length - 1 &&
             !this.isCellMerged(this.selectedRow + 1, this.selectedCol)
    },
    
    canMergeRow() {
      return this.selectedRow !== null && this.tableData.rows[0].cells.length > 1
    },
    
    canMergeColumn() {
      return this.selectedCol !== null && this.tableData.rows.length > 1
    },
    
    canSplit() {
      if (this.selectedRow === null || this.selectedCol === null) return false
      return this.isMergeStartCell(this.selectedRow, this.selectedCol)
    }
  },
  watch: {
    // 监听组件内容变化，更新表格数据
    'component.content': {
      handler(newContent) {
        if (newContent && newContent.rows) {
          this.tableData = deepClone(newContent)
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 初始化表格数据
    initializeTableData() {
      if (!this.component.content || !this.component.content.rows) {
        this.tableData = deepClone(this.defaultConfig)
        this.saveTableConfig()
      } else {
        this.tableData = deepClone(this.component.content)
      }
    },
    
    // 获取行样式
    getRowStyle(rowIndex) {
      const row = this.tableData.rows[rowIndex]
      return {
        height: `${row.height}px`
      }
    },
    
    // 获取单元格样式
    getCellStyle(rowIndex, colIndex) {
      const cell = this.getCell(rowIndex, colIndex)
      const baseStyle = {
        border: '1px dashed #e0e0e0',
        padding: '4px',
        position: 'relative',
        verticalAlign: 'top',
        width: `${cell.width}px`,
        height: `${cell.height}px`,
        boxSizing: 'border-box'
      }
      
      // 隐藏被合并的单元格
      if (this.isCellMerged(rowIndex, colIndex) && !this.isMergeStartCell(rowIndex, colIndex)) {
        baseStyle.display = 'none'
      }
      
      return baseStyle
    },
    
    // 获取单元格
    getCell(rowIndex, colIndex) {
      if (rowIndex >= 0 && rowIndex < this.tableData.rows.length &&
          colIndex >= 0 && colIndex < this.tableData.rows[rowIndex].cells.length) {
        return this.tableData.rows[rowIndex].cells[colIndex] || {}
      }
      return { width: 150, height: 100, components: [] }
    },
    
    // 获取单元格中的组件（考虑合并单元格）
    getCellComponents(rowIndex, colIndex) {
      if (this.isCellMerged(rowIndex, colIndex)) {
        const mergeInfo = this.findMergeInfo(rowIndex, colIndex)
        if (mergeInfo) {
          return this.getCell(mergeInfo.startRow, mergeInfo.startCol).components || []
        }
      }
      return this.getCell(rowIndex, colIndex).components || []
    },
    
    // 检查单元格是否被选中
    isCellSelected(rowIndex, colIndex) {
      return this.selectedRow === rowIndex && this.selectedCol === colIndex
    },
    
    // 检查是否为拖拽目标
    isDropTarget(rowIndex, colIndex) {
      return this.dropTargetCell && 
             this.dropTargetCell.row === rowIndex && 
             this.dropTargetCell.col === colIndex
    },
    
    // 选择单元格
    selectCell(rowIndex, colIndex, event) {
      console.log('selectCell', rowIndex, colIndex, event)
      if (this.isCellMerged(rowIndex, colIndex) && !this.isMergeStartCell(rowIndex, colIndex)) {
        // 如果点击的是被合并的单元格，选择合并的起始单元格
        const mergeInfo = this.findMergeInfo(rowIndex, colIndex)
        if (mergeInfo) {
          this.selectedRow = mergeInfo.startRow
          this.selectedCol = mergeInfo.startCol
        }
      } else {
        this.selectedRow = rowIndex
        this.selectedCol = colIndex
      }
      
      this.selectedCell = this.getCell(this.selectedRow, this.selectedCol)
      this.hideContextMenu()
    },
    
    // 显示右键菜单
    showContextMenu(rowIndex, colIndex, event) {
      event.preventDefault()
      
      this.selectCell(rowIndex, colIndex, event)
      
      this.contextMenu = {
        visible: true,
        row: rowIndex,
        col: colIndex,
        style: {
          left: `${event.clientX}px`,
          top: `${event.clientY}px`
        }
      }
    },
    
    // 隐藏右键菜单
    hideContextMenu() {
      this.contextMenu.visible = false
    },
    
    // 插入列
    insertColumn(position) {
      if (this.selectedCol === null) return
      
      const insertIndex = position === 'left' ? this.selectedCol : this.selectedCol + 1
      const colWidth = 150 // 默认列宽
      
      // 为每一行插入单元格
      this.tableData.rows.forEach(row => {
        row.cells.splice(insertIndex, 0, {
          width: colWidth,
          height: row.height,
          components: []
        })
      })
      
      // 调整合并信息
      this.adjustMergesAfterColumnInsert(insertIndex)
      
      this.selectedCol = insertIndex
      this.saveTableConfig()
      this.hideContextMenu()
      
      this.$message.success(`已${position === 'left' ? '左侧' : '右侧'}插入列`)
    },
    
    // 插入行
    insertRow(position) {
      if (this.selectedRow === null) return
      
      const insertIndex = position === 'above' ? this.selectedRow : this.selectedRow + 1
      const rowHeight = 100 // 默认行高
      const colCount = this.tableData.rows[0].cells.length
      
      // 插入行配置
      const newRow = {
        height: rowHeight,
        cells: Array(colCount).fill().map(() => ({
          width: 150,
          height: rowHeight,
          components: []
        }))
      }
      
      this.tableData.rows.splice(insertIndex, 0, newRow)
      
      // 调整合并信息
      this.adjustMergesAfterRowInsert(insertIndex)
      
      this.selectedRow = insertIndex
      this.saveTableConfig()
      this.hideContextMenu()
      
      this.$message.success(`已${position === 'above' ? '上方' : '下方'}插入行`)
    },
    
    // 删除列
    deleteColumn() {
      if (this.selectedCol === null || this.tableData.rows[0].cells.length <= 1) {
        this.$message.warning('至少保留一列')
        return
      }
      
      this.tableData.rows.forEach(row => {
        row.cells.splice(this.selectedCol, 1)
      })
      
      // 调整合并信息
      this.adjustMergesAfterColumnDelete(this.selectedCol)
      
      this.selectedCol = Math.min(this.selectedCol, this.tableData.rows[0].cells.length - 1)
      this.saveTableConfig()
      this.hideContextMenu()
      
      this.$message.success('已删除列')
    },
    
    // 删除行
    deleteRow() {
      if (this.selectedRow === null || this.tableData.rows.length <= 1) {
        this.$message.warning('至少保留一行')
        return
      }
      
      this.tableData.rows.splice(this.selectedRow, 1)
      
      // 调整合并信息
      this.adjustMergesAfterRowDelete(this.selectedRow)
      
      this.selectedRow = Math.min(this.selectedRow, this.tableData.rows.length - 1)
      this.saveTableConfig()
      this.hideContextMenu()
      
      this.$message.success('已删除行')
    },
    
    // 合并单元格
    mergeCells(direction) {
      if (this.selectedRow === null || this.selectedCol === null) return
      
      let mergeInfo = null
      
      switch (direction) {
        case 'right':
          if (this.canMergeRight) {
            mergeInfo = {
              startRow: this.selectedRow,
              startCol: this.selectedCol,
              endRow: this.selectedRow,
              endCol: this.selectedCol + 1
            }
          } else {
            this.$message.warning('无法合并右侧单元格')
            return
          }
          break
          
        case 'below':
          if (this.canMergeBelow) {
            mergeInfo = {
              startRow: this.selectedRow,
              startCol: this.selectedCol,
              endRow: this.selectedRow + 1,
              endCol: this.selectedCol
            }
          } else {
            this.$message.warning('无法合并下方单元格')
            return
          }
          break
          
        case 'row':
          if (this.canMergeRow) {
            mergeInfo = {
              startRow: this.selectedRow,
              startCol: this.selectedCol,
              endRow: this.selectedRow,
              endCol: this.tableData.rows[0].cells.length - 1
            }
          } else {
            this.$message.warning('无法合并整行')
            return
          }
          break
          
        case 'column':
          if (this.canMergeColumn) {
            mergeInfo = {
              startRow: this.selectedRow,
              startCol: this.selectedCol,
              endRow: this.tableData.rows.length - 1,
              endCol: this.selectedCol
            }
          } else {
            this.$message.warning('无法合并整列')
            return
          }
          break
      }
      
      if (mergeInfo) {
        this.addMerge(mergeInfo)
        this.saveTableConfig()
        this.$message.success('单元格合并成功')
      }
      
      this.hideContextMenu()
    },
    
    // 拆分单元格
    splitCell() {
      if (!this.canSplit) {
        this.$message.warning('当前单元格未被合并')
        return
      }
      
      // 移除包含当前单元格的合并信息
      this.tableData.merges = this.tableData.merges.filter(merge => 
        !(this.selectedRow >= merge.startRow && this.selectedRow <= merge.endRow &&
          this.selectedCol >= merge.startCol && this.selectedCol <= merge.endCol)
      )
      
      this.saveTableConfig()
      this.hideContextMenu()
      this.$message.success('单元格拆分成功')
    },
    
    // 显示单元格属性对话框
    showCellProperties() {
      if (this.selectedRow === null || this.selectedCol === null) return
      
      const cell = this.getCell(this.selectedRow, this.selectedCol)
      this.cellPropertiesDialog.data = {
        width: cell.width,
        height: cell.height
      }
      this.cellPropertiesDialog.visible = true
      this.hideContextMenu()
    },
    
    // 更新单元格属性
    updateCellProperties() {
      if (this.selectedRow === null || this.selectedCol === null) return
      
      const cell = this.getCell(this.selectedRow, this.selectedCol)
      cell.width = this.cellPropertiesDialog.data.width
      cell.height = this.cellPropertiesDialog.data.height
      
      this.saveTableConfig()
      this.cellPropertiesDialog.visible = false
      this.$message.success('单元格属性已更新')
    },
    
    // 添加合并信息
    addMerge(mergeInfo) {
      // 检查是否与现有合并冲突
      const hasConflict = this.tableData.merges.some(merge => 
        this.isMergeOverlap(merge, mergeInfo)
      )
      
      if (!hasConflict) {
        this.tableData.merges.push(mergeInfo)
        
        // 合并单元格时，将被合并单元格的组件移动到起始单元格
        this.moveComponentsToMergeStart(mergeInfo)
      } else {
        this.$message.warning('合并区域与现有合并冲突')
      }
    },
    
    // 移动组件到合并起始单元格
    moveComponentsToMergeStart(mergeInfo) {
      const startCell = this.getCell(mergeInfo.startRow, mergeInfo.startCol)
      
      for (let row = mergeInfo.startRow; row <= mergeInfo.endRow; row++) {
        for (let col = mergeInfo.startCol; col <= mergeInfo.endCol; col++) {
          if (row === mergeInfo.startRow && col === mergeInfo.startCol) continue
          
          const cell = this.getCell(row, col)
          if (cell.components && cell.components.length > 0) {
            startCell.components = [...(startCell.components || []), ...cell.components]
            cell.components = []
          }
        }
      }
    },
    
    // 检查合并是否重叠
    isMergeOverlap(merge1, merge2) {
      return !(
        merge1.endRow < merge2.startRow ||
        merge1.startRow > merge2.endRow ||
        merge1.endCol < merge2.startCol ||
        merge1.startCol > merge2.endCol
      )
    },
    
    // 检查单元格是否被合并
    isCellMerged(rowIndex, colIndex) {
      return this.tableData.merges.some(merge => 
        rowIndex >= merge.startRow && rowIndex <= merge.endRow &&
        colIndex >= merge.startCol && colIndex <= merge.endCol
      )
    },
    
    // 检查是否为合并起始单元格
    isMergeStartCell(rowIndex, colIndex) {
      return this.tableData.merges.some(merge => 
        rowIndex === merge.startRow && colIndex === merge.startCol
      )
    },
    
    // 查找单元格所在的合并信息
    findMergeInfo(rowIndex, colIndex) {
      return this.tableData.merges.find(merge => 
        rowIndex >= merge.startRow && rowIndex <= merge.endRow &&
        colIndex >= merge.startCol && colIndex <= merge.endCol
      )
    },
    
    // 获取合并行跨度
    getMergeRowSpan(rowIndex, colIndex) {
      const mergeInfo = this.findMergeInfo(rowIndex, colIndex)
      if (mergeInfo && this.isMergeStartCell(rowIndex, colIndex)) {
        return mergeInfo.endRow - mergeInfo.startRow + 1
      }
      return 1
    },
    
    // 获取合并列跨度
    getMergeColSpan(rowIndex, colIndex) {
      const mergeInfo = this.findMergeInfo(rowIndex, colIndex)
      if (mergeInfo && this.isMergeStartCell(rowIndex, colIndex)) {
        return mergeInfo.endCol - mergeInfo.startCol + 1
      }
      return 1
    },
    
    // 处理拖拽放置
    handleDrop(rowIndex, colIndex, event) {
      event.preventDefault()
      
      if (this.isCellMerged(rowIndex, colIndex) && !this.isMergeStartCell(rowIndex, colIndex)) {
        const mergeInfo = this.findMergeInfo(rowIndex, colIndex)
        if (mergeInfo) {
          rowIndex = mergeInfo.startRow
          colIndex = mergeInfo.startCol
        }
      }
      
      const componentType = event.dataTransfer.getData('text/plain')
      if (componentType) {
        this.addComponentToCell(rowIndex, colIndex, componentType, event)
      }
      
      this.dropTargetCell = null
    },
    
    // 处理拖拽经过
    handleDragOver(rowIndex, colIndex, event) {
      event.preventDefault()
      event.dataTransfer.dropEffect = 'copy'
    },
    
    // 处理拖拽进入
    handleDragEnter(rowIndex, colIndex, event) {
      event.preventDefault()
      this.dropTargetCell = { row: rowIndex, col: colIndex }
    },
    
    // 处理拖拽离开
    handleDragLeave(rowIndex, colIndex, event) {
      if (!this.$refs.tableContainer.contains(event.relatedTarget)) {
        this.dropTargetCell = null
      }
    },
    
    // 添加组件到单元格
    addComponentToCell(rowIndex, colIndex, componentType, event) {
      const cell = this.getCell(rowIndex, colIndex)
      if (!cell.components) {
        cell.components = []
      }
      
      // 创建新组件
      const newComponent = this.createComponent(componentType, event)
      cell.components.push(newComponent)
      
      this.saveTableConfig()
      this.$message.success(`已将${this.getComponentName(componentType)}添加到单元格`)
    },
    
    // 创建组件
    createComponent(type, event) {
      console.log('createComponent', type, event)
      const baseComponent = {
        id: `COMP_${generateId(8)}`,
        type,
        position: { x: 10, y: 10, width: 120, height: 30 },
        style: {},
        content: {},
        zIndex: 1
      }

      // 根据组件类型设置默认内容
      switch (type) {
        case 'text':
          baseComponent.content = {
            text: '文本内容',
            fontSize: 14,
            fontWeight: 'normal',
            align: 'left',
            color: '#000000'
          }
          break
        case 'parameter':
          baseComponent.content = {
            paramCode: '',
            displayName: '',
            format: 'value',
            precision: 2
          }
          break
        case 'number':
          baseComponent.content = {
            paramCode: '',
            displayName: '',
            showUnit: true,
            precision: 2
          }
          break
        // 其他组件类型...
      }

      return baseComponent
    },
    
    // 获取组件名称
    getComponentName(type) {
      const nameMap = {
        text: '文本',
        parameter: '参数',
        number: '数值',
        multiMeasure: '多测次',
        dynamicTable: '动态表格',
        multiParam: '多参数',
        paramGroup: '参数组',
        image: '图片'
      }
      return nameMap[type] || type
    },
    
    // 处理组件选择
    handleComponentSelect(component) {
      this.$emit('select-component', component)
    },
    
    // 处理组件更新
    handleComponentUpdate(componentId, updates) {
      this.$emit('update-component', componentId, updates)
    },
    
    // 处理组件删除
    handleComponentRemove(componentId) {
      // 从所有单元格中查找并删除组件
      this.tableData.rows.forEach(row => {
        row.cells.forEach(cell => {
          if (cell.components) {
            const index = cell.components.findIndex(comp => comp.id === componentId)
            if (index !== -1) {
              cell.components.splice(index, 1)
            }
          }
        })
      })
      
      this.saveTableConfig()
      this.$emit('component-remove', componentId)
    },
    
    // 获取表格总宽度
    getTotalTableWidth() {
      if (this.tableData.rows.length === 0) return 0
      return this.tableData.rows[0].cells.reduce((total, cell) => total + cell.width, 0)
    },
    
    // 保存表格配置
    saveTableConfig() {
      this.$emit('update-component', this.component.id, {
        content: deepClone(this.tableData)
      })
    },
    
    // 调整合并信息的方法
    adjustMergesAfterColumnInsert(insertIndex) {
      this.tableData.merges.forEach(merge => {
        if (merge.startCol >= insertIndex) {
          merge.startCol++
          merge.endCol++
        } else if (merge.endCol >= insertIndex) {
          merge.endCol++
        }
      })
    },
    
    adjustMergesAfterRowInsert(insertIndex) {
      this.tableData.merges.forEach(merge => {
        if (merge.startRow >= insertIndex) {
          merge.startRow++
          merge.endRow++
        } else if (merge.endRow >= insertIndex) {
          merge.endRow++
        }
      })
    },
    
    adjustMergesAfterColumnDelete(deleteIndex) {
      this.tableData.merges = this.tableData.merges.filter(merge => {
        if (deleteIndex >= merge.startCol && deleteIndex <= merge.endCol) {
          if (merge.startCol === merge.endCol) {
            return false
          } else if (deleteIndex === merge.startCol) {
            merge.startCol++
          } else if (deleteIndex === merge.endCol) {
            merge.endCol--
          } else {
            this.tableData.merges.push({
              startRow: merge.startRow,
              startCol: deleteIndex + 1,
              endRow: merge.endRow,
              endCol: merge.endCol
            })
            merge.endCol = deleteIndex - 1
          }
        } else if (merge.startCol > deleteIndex) {
          merge.startCol--
          merge.endCol--
        } else if (merge.endCol > deleteIndex) {
          merge.endCol--
        }
        return true
      })
    },
    
    adjustMergesAfterRowDelete(deleteIndex) {
      this.tableData.merges = this.tableData.merges.filter(merge => {
        if (deleteIndex >= merge.startRow && deleteIndex <= merge.endRow) {
          if (merge.startRow === merge.endRow) {
            return false
          } else if (deleteIndex === merge.startRow) {
            merge.startRow++
          } else if (deleteIndex === merge.endRow) {
            merge.endRow--
          } else {
            this.tableData.merges.push({
              startRow: deleteIndex + 1,
              startCol: merge.startCol,
              endRow: merge.endRow,
              endCol: merge.endCol
            })
            merge.endRow = deleteIndex - 1
          }
        } else if (merge.startRow > deleteIndex) {
          merge.startRow--
          merge.endRow--
        } else if (merge.endRow > deleteIndex) {
          merge.endRow--
        }
        return true
      })
    }
  },
  
  mounted() {
    // 初始化表格数据
    this.initializeTableData()
    
    // 添加全局点击事件监听，用于隐藏右键菜单
    document.addEventListener('click', this.hideContextMenu)
  },
  
  beforeDestroy() {
    document.removeEventListener('click', this.hideContextMenu)
  }
}
</script>

<style scoped>
.layout-table-renderer {
  font-family: Arial, sans-serif;
}

.editable-table-container {
  overflow: auto;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 4px;
}

.layout-table {
  background: white;
  user-select: none;
}

.layout-cell {
  position: relative;
  cursor: pointer;
  transition: all 0.2s ease;
}

.layout-cell.selected {
  background-color: #ecf5ff !important;
  box-shadow: inset 0 0 0 2px #409eff;
}

.layout-cell.merged {
  background-color: #f0f9ff;
}

.layout-cell.drop-target {
  background-color: #f0f9ff;
  box-shadow: inset 0 0 0 2px #67c23a;
}

.cell-content {
  width: 100%;
  height: 100%;
  position: relative;
  min-height: 60px;
}

.merged-cell-content {
  width: 100%;
  height: 100%;
  position: relative;
}

.empty-cell-hint {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #c0c4cc;
  font-size: 12px;
  pointer-events: none;
}

.empty-cell-hint i {
  display: block;
  font-size: 20px;
  margin-bottom: 4px;
}

.cell-size-info {
  position: absolute;
  bottom: 2px;
  right: 2px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 1px 4px;
  border-radius: 2px;
  font-size: 10px;
  pointer-events: none;
}

/* 右键菜单 */
.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 10000;
  min-width: 160px;
  max-width: 240px;
}

.menu-section {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.menu-section:last-child {
  border-bottom: none;
}

.menu-title {
  padding: 4px 12px;
  font-size: 12px;
  color: #909399;
  font-weight: bold;
}

.menu-item {
  padding: 8px 12px;
  font-size: 13px;
  color: #606266;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: background-color 0.2s;
}

.menu-item:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.menu-item.disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.menu-item.disabled:hover {
  background-color: transparent;
  color: #c0c4cc;
}

.menu-item i {
  margin-right: 8px;
  width: 14px;
  text-align: center;
}

.preview-layout-table {
  background: white;
}

.preview-layout-table td {
  border: 1px solid #e0e0e0;
  padding: 4px;
  vertical-align: top;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .context-menu {
    min-width: 140px;
    max-width: 200px;
  }
  
  .menu-item {
    padding: 6px 10px;
    font-size: 12px;
  }
}
</style>